package logic

import (
	"context"
	"encoding/base64"
	"fmt"
	"io/ioutil"
	"net/http"

	"github.com/comfygpt-backend-go/common/consts"
	"github.com/comfygpt-backend-go/common/jwtx"
	"github.com/comfygpt-backend-go/service/user-api/internal/svc"
	"github.com/comfygpt-backend-go/service/user-api/internal/types"

	"github.com/comfygpt-backend-go/service/user-rpc/userclient"

	"github.com/zeromicro/go-zero/core/logc"
	"github.com/zeromicro/go-zero/core/logx"
)

type UploadAvatarLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUploadAvatarLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadAvatarLogic {
	return &UploadAvatarLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UploadAvatarLogic) UploadAvatar(req *http.Request) (resp *types.CommonResp, err error) {
	resp = &types.CommonResp{
		Code:    int64(consts.SUCCESS),
		Message: consts.WrongMessageEn[consts.SUCCESS],
	}
	// 1. 从参数中获取图片文件，使用base64编码为string
	file, _, err := req.FormFile("avatar")
	if err != nil {
		logc.Errorf(l.ctx, "req.FormFile err: %v", err)
		return nil, err
	}
	defer file.Close()

	// 读取文件内容
	fileBytes, err := ioutil.ReadAll(file)
	if err != nil {
		logc.Errorf(l.ctx, "ioutil.ReadAll err: %v", err)
		return nil, err
	}

	// 将文件内容编码为base64字符串
	imageStr := base64.StdEncoding.EncodeToString(fileBytes)
	in := &userclient.UploadRequest{
		UserId:     jwtx.GetUidFromCtx(l.ctx),
		Image:      imageStr,
		ObjectName: fmt.Sprintf("%d_avatar.png", jwtx.GetUidFromCtx(l.ctx)),
	}

	// 2. 调用user-rpc服务，上传图片到minio
	_, err = l.svcCtx.UserRpc.Upload(l.ctx, in)
	if err != nil {
		resp.Code = int64(consts.FAIL)
		resp.Message = err.Error()
		return resp, err
	}

	return
}
